const Service = require('egg').Service;
const validateUtil = require('@jianghujs/jianghu/app/common/validateUtil');
const idGenerateUtil = require('@jianghujs/jianghu/app/common/idGenerateUtil');
const { BizError, errorInfoEnum } = require('../constant/error');
const { tableEnum } = require('../constant/constant');
const _ = require('lodash');
const dayjs = require('dayjs');

// beforeHook，afterHook都写这里

class HookService extends Service {
  // 保险单列表
  async appendInsuranceTicketList() {
    const { resultData } = this.ctx.response.body.appData;
    const { jianghuKnex } = this.app;
    let ticketList = await jianghuKnex('ticket', this.ctx).select();
    for (let i = 0; i < resultData.rows.length; i++) {
      let row = resultData.rows[i];
      row[`insurancePaymentTicket`] = ticketList.filter(ticket => ticket.ticketType == "保险付款" && ticket.ticketBizId == row[`insuranceId`]);
      row[`insurancePaymentTicketCount`] = row[`insurancePaymentTicket`].length;
    }
  }

  // 保养单列表
  async appendMaintenanceTicketList() {
    const { resultData } = this.ctx.response.body.appData;
    const { jianghuKnex } = this.app;
    let ticketList = await jianghuKnex('ticket', this.ctx).select();
    for (let i = 0; i < resultData.rows.length; i++) {
      let row = resultData.rows[i];
      row[`maintenancePaymentTicket`] = ticketList.filter(ticket => ticket.ticketType == "保养付款" && ticket.ticketBizId == row[`maintenanceId`]);
      row[`maintenancePaymentTicketCount`] = row[`maintenancePaymentTicket`].length;
    }
  }

  // 合同单列表
  async appendContractTicketList() {
    const { resultData } = this.ctx.response.body.appData;
    const { jianghuKnex } = this.app;
    let ticketList = await jianghuKnex('ticket').select();

    const getTicketFilterList = (row, ticketType) => {
      return ticketList.filter(ticket => ticket.ticketType == ticketType && ticket.ticketBizId == row[`contractId`])
    }

    for (let i = 0; i < resultData.rows.length; i++) {
      let row = resultData.rows[i];

      row.getCarTicket = getTicketFilterList(row, '发车申请');
      row.returnCarTicket = getTicketFilterList(row, '退车申请');
      row.receiptTicket  = getTicketFilterList(row, '发车收款');
      row.paymentTicket = getTicketFilterList(row, '退车付款');
    }
  }

  // 添加客户信息
  async appendCustomerInfo() {
    const { resultData } = this.ctx.response.body.appData;

    const customerList = await this.app.jianghuKnex('customer').select();

    _.map(resultData.rows, (row) => {
      row.customerInfo = customerList.find(item => item.customerId === row.customerId);
    })
  }
}

module.exports = HookService;